package stackdemo;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2023-12-22
 * Time: 16:25
 */

//栈的模拟实现:
public class MyStack {

    //Stack栈可以通过数组进行实现
    public static final int DEFAULT_CAPACITY = 10;
    int usedSize;
    public int[] elem;

    //构造函数
    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }


    private boolean isFull(){
        return usedSize == elem.length;
    }

    //压栈、入栈操作:
    public void push(int val) {
        //先判断栈是否以满
        if(isFull()) {
            //数组进行二倍扩容
            this.elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize++] = val;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    //弹出:
    private int pop() {
        //先判断栈是否为空，如果为空则无法出栈:
        if(isEmpty()) {
            throw new EmptyStackException("栈为空，无法弹出");
        }
        usedSize--;
        return elem[usedSize];
    }

    //
    public int peek() {
        //先判断栈是否为空，如果为空则无法出栈:
        if(isEmpty()) {
            throw new EmptyStackException("栈为空，无法弹出");
        }
        return elem[usedSize-1];
    }

    @Override
    public String toString() {
        return "MyStack{" +
                "usedSize=" + usedSize +
                ", elem=" + Arrays.toString(elem) +
                '}';
    }
}
